#!/bin/bash
set -xe

cd $(dirname $0)/..

. ./scripts/test-helpers

if [ -z "${K3S_IMAGE}" ]; then
    echo 'K3S_IMAGE environment variable should be defined'
    exit 1
fi

# ---

cleanup() {
    exit_status=$?
    set +e
    echo 'Cleaning up'
    trap - EXIT
    [ -n "$SONOBUOY_PID" ] && kill $SONOBUOY_PID 2>/dev/null
    if [ "${exit_status}" -ne "0" ]; then
        dump-logs
    fi
    docker rm -f ${CONTAINERS} 2>/dev/null
    rm ${KUBECONFIG}
    exit ${exit_status}
}
trap cleanup EXIT

# ---

K3S_PORT=$(timeout --foreground 5s bash -c get-port)
OUTPUT=$(pwd)/sonobuoy-output/${K3S_PORT}
LOGS=$(pwd)/logs/$$
E2E="${OUTPUT}/e2e"
E2E_LOG='plugins/e2e/results/global/e2e.log'
RESULTS="${E2E}/${E2E_LOG}"

SECRET=random-$((100000 + RANDOM % 999999))
export K3S_AGENT=k3s-agent-${K3S_PORT}
export K3S_SERVER=k3s-server-${K3S_PORT}
export CONTAINERS="${K3S_SERVER} ${K3S_AGENT}"
export KUBECONFIG=${OUTPUT}/kubeconfig.yaml

mkdir -p ${OUTPUT}

# ---

docker run -d --name ${K3S_SERVER} --privileged \
    -p 127.0.0.1:${K3S_PORT}:${K3S_PORT} \
    -e K3S_CLUSTER_SECRET=${SECRET} \
    -e K3S_DEBUG=true \
    ${K3S_IMAGE} server --no-deploy=traefik --https-listen-port=${K3S_PORT}

K3S_IP=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' ${K3S_SERVER})
echo "Started ${K3S_SERVER} @ ${K3S_IP}:${K3S_PORT}"

docker exec ${K3S_SERVER} check-config || true
timeout --foreground 1m bash -c wait-for-kubeconfig
verify-valid-versions ${K3S_SERVER}

# ---

docker run -d --name ${K3S_AGENT} --privileged \
    -e K3S_CLUSTER_SECRET=${SECRET} \
    -e K3S_URL=https://${K3S_IP}:${K3S_PORT} \
    ${K3S_IMAGE} agent

echo "Started ${K3S_AGENT}"

# ---

timeout --foreground 1m bash -c 'wait-for-nodes 2'
timeout --foreground 3m bash -c 'wait-for-services coredns local-path-provisioner metrics-server'

if [ "$ARCH" = 'arm' ]; then
    echo "Aborting sonobuoy tests, images not available for $ARCH"
    exit 0
fi

echo 'Starting sonobuoy tests'
sonobuoy-test "${@}"
